package com.gzc.just.play.last.war.common.handler;

import com.gzc.just.play.last.war.common.serializer.MessageSerializer;
import com.gzc.just.play.last.war.common.thread.VirtualThreadMessageProcessor;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 基于线程的消息路由器
 * 将消息处理从IO线程中分离，使用虚拟线程处理业务逻辑
 */
public class ThreadedMessageRouter {
    private static final Logger logger = LoggerFactory.getLogger(ThreadedMessageRouter.class);
    
    // 消息ID到处理器的映射
    private final ConcurrentHashMap<Integer, SimpleMessageHandler> handlers = new ConcurrentHashMap<>();
    
    // 消息序列化器
    private final MessageSerializer messageSerializer;
    
    // 虚拟线程消息处理器
    private final VirtualThreadMessageProcessor messageProcessor;
    
    /**
     * 构造函数
     * @param messageSerializer 消息序列化器
     * @param threadPoolSize 线程池大小
     */
    public ThreadedMessageRouter(MessageSerializer messageSerializer, int threadPoolSize) {
        this.messageSerializer = messageSerializer;
        this.messageProcessor = new VirtualThreadMessageProcessor("MessageProcessor", threadPoolSize);
        
        // 启动虚拟线程处理器
        messageProcessor.start();
        logger.info("Created ThreadedMessageRouter with {} virtual threads", threadPoolSize);
    }
    
    /**
     * 注册消息处理器
     * @param handler 消息处理器
     */
    public void registerHandler(SimpleMessageHandler handler) {
        handlers.put(handler.getMessageId(), handler);
        
        // 创建基于线程的处理器适配器
        ThreadedMessageHandlerAdapter threadedHandler = new ThreadedMessageHandlerAdapter(handler, messageProcessor);
        logger.info("Registered message handler: {} for message ID: {}",
                   handler.getName(), handler.getMessageId());
    }
    
    /**
     * 处理接收到的消息
     * @param ctx Netty通道上下文
     * @param messageId 消息ID
     * @param bytes 消息字节数据
     */
    public void handleMessage(ChannelHandlerContext ctx, int messageId, byte[] bytes) {
        try {
            // 查找对应的处理器
            SimpleMessageHandler handler = handlers.get(messageId);
            if (handler == null) {
                logger.warn("No handler found for message ID: {}", messageId);
                return;
            }
            
            // 检查是否有反序列化器支持此消息
            if (messageSerializer == null) {
                logger.warn("No message serializer available");
                return;
            }
            
            // 提交任务到虚拟线程处理队列
            messageProcessor.submitTask(messageId, bytes, ctx, new ThreadedMessageHandlerAdapter(handler, messageProcessor));
            
        } catch (Exception e) {
            logger.error("Error handling message with ID: {}", messageId, e);
        }
    }
    
    /**
     * 停止消息路由器
     */
    public void stop() {
        if (messageProcessor != null) {
            messageProcessor.stop();
        }
    }
    
    /**
     * 获取已注册的处理器数量
     * @return 处理器数量
     */
    public int getHandlerCount() {
        return handlers.size();
    }
    
    /**
     * 检查是否有指定ID的处理器
     * @param messageId 消息ID
     * @return 是否存在处理器
     */
    public boolean hasHandler(int messageId) {
        return handlers.containsKey(messageId);
    }
    
    /**
     * 获取当前队列大小
     * @return 待处理的消息数量
     */
    public int getQueueSize() {
        return messageProcessor.getQueueSize();
    }
}